<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2023/2/27
 * Time: 11:15
 */

namespace App\Rep\Rbac;

use App\Models\Employee;
use App\Models\ManagementCard;
use App\Models\Rbac\Role;
use App\Models\Rbac\UserRole;
use App\Rep\EmployeeRep;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;
use Cisco\Aliyunsms\Facades\Aliyunsms;
use App\Models\Rbac\User;



class UserRep
{

    /** @var float|int token 有效期 */
    const TOKEN_EXPIRE = 3600*24*3;
    /**
     * Notes:连接Redis
     */
    static function redisConnection(){
        return Redis::connection("user_token")->client();
    }

    /**
     * 短信验证码登录
     * Notes: 校验账号是否存在
     */
    static public function checkAccount($phone){
        return User::where('phone',$phone)->first();
    }


    /**
     * 短信验证码登录
     * Notes: 保存登录信息 & 返回用户token
     */
    public function signIn($phone,$verification_code){

        if (empty($account)) {
            return ['code'=>1010,'data'=>'','msg'=>''];
        }
        //获取redis里的验证码
        $v_code = $this->getVerificationCodeByPhone($phone);
        if(empty($v_code)){
            return ['code'=>1010,'data'=>'','msg'=>'验证码失效'];
        }
        if($v_code != $verification_code){
            return ['code'=>1008,'data'=>'','msg'=>'验证码错误'];
        }
        //验证手机号
        $account = self::checkAccount($phone);
        if($account->status == 2){
            return ['code'=>1013,'data'=>'','msg'=>'该账户正在审核中'];
        }elseif($account->status == 3){
            return ['code'=>1014,'data'=>'','msg'=>'该账户正审核未通过'];
        }

        $token = md5($account->phone.uniqid());
        $account->token = $token;
        $account->last_login_time = date('Y-m-d h:i:s', time());
        $account->save();

        $saveData = self::getUserKeysValue($account);

        self::resetUserTokenValue($token,$saveData);
        return ['code'=>0,'data'=>$saveData,'msg'=>'success'];
    }

    /**获取redis里的短信验证码**/
    public function getVerificationCodeByPhone($phone){
        $redis = self::redisConnection();
        return $redis->get(':sms_code:'.$phone);
    }

    /**
     * Notes: 获取管理员用户值
     * 公司名称，token，最后登录时间，最后登录IP，VIP过期时间，手机号
     */
    static function getUserKeysValue(User $user){
        return  $user->getKeys("id",'username',"company_name","token",'last_login_time','last_login_ip','expire_time','phone','parent_username','is_primary');
    }

    /**
     * 获取用户角色名称
     * @param $user_id
     * @return mixed
     */
    static function getRoleNameByUserId($user_id){
        $user_info = User::where('id',$user_id)->with(['role'])->first()->toArray();
        $role_name = $user_info['role'][0]['name'];
        return  $role_name;
    }

    /**
     * Notes: 重置用户Token数据
     */
    static function resetUserTokenValue($token,$data){
        $redis = self::redisConnection();
        $redis->setex($token,self::TOKEN_EXPIRE,json_encode($data,JSON_UNESCAPED_UNICODE));
    }

    /**
     * Notes: 重置token有效期
     * @param $token
     * @return bool
     */
    static function resetUserTokenExpire($token){
        return self::redisConnection()->expire($token,self::TOKEN_EXPIRE);
    }


    /**
     * Notes: 删除redis token
     * @param $token
     * @return int
     */
    static function removeToken($token){
        return self::redisConnection()->del($token);
    }

    /**
     * Notes: 删除数据库token
     */
    static function removeDBToken($user_id){
        $admin = User::find($user_id);
        $admin->token = "";
        $admin->save();
        return $admin;
    }

    /**
     * Notes: 根据token从redis获取用户信息
     * @param $token
     * @return mixed
     */
    static function getUserInfoForToken($token){
        return json_decode(self::redisConnection()->get($token),true);
    }


    /**
     * 发送短信
     * @param $phone
     * @return array
     */
    public function sendSMSRep($phone){
        $SignName    = env('ALIYUN_SIGN_NAME');          //模板签名
        $TemplateCode= env('ALIYUN_TEMPLATECODE');         //模板CODE
        //阿里云模板里面的变量
        $TemplateParam = [
            "code"    => rand(100000,999999),
            "product" => "dsd"
        ];
        $send = Aliyunsms::sendSms(strval($phone), $SignName, $TemplateCode, $TemplateParam);
        if ($send->Code == 'OK') {
            $this->redis->setex(':sms_code:'.$phone,600,$TemplateParam['code']);
            $res = ['code'=>0,'msg'=>'success','data'=>''];
        } else {

            $res = ['code'=>3004,'msg'=>$send->Message,'data'=>$send];
        }
        return $res;
    }

    /**账号密码登录**/
    public function signInPwdRep($parent_username,$child_username,$password,$is_primary){
        if($is_primary == 1){
            $info = User::where('username', $parent_username)->first();
        }elseif($is_primary == 2){
            $info = User::where('username', $child_username)->first();
        }
        if (!$info) {
            return ['code'=>1000,'msg'=>'账号或密码错误1','data'=>$info];
        }
        // 密码校验
        if ($password != $info['password']) {
            return ['code'=>1000,'msg'=>'账号或密码错误2','data'=>$info];
        }
        // 使用状态校验
        if ($info['status'] != 1) {
            return ['code'=>1009,'msg'=>'账户不可用,请联系管理员','data'=>[]];
        }


        $token = md5($info->username.$info->password.uniqid());
        $info->token = $token;
        $info->expire_time = date('Y-m-d h:i:s', time() + self::TOKEN_EXPIRE);
        $info->last_login_time = date('Y-m-d h:i:s', time());
        $info->last_login_ip = get_client_ip();
        $info->save();

        $saveData = self::getUserKeysValue($info);
        $saveData['role_name'] = self::getRoleNameByUserId($info->id);
        self::resetUserTokenValue($token,$saveData);

        return ['code'=>0,'msg'=>'','data'=>$saveData];

    }


    /**
     * 员工卡号登录
     * @param $card_number
     * @return array
     */
    public function signInCardNumberRep($params){
        $card_number = $params['card_number'];

        //管理卡登陆
        $management_card = ManagementCard::where('card_number',$card_number)->where('is_del',2)->first();
        if($management_card){
            $management_card->is_admin = 1;
            return ['code'=>0,'msg'=>'','data'=>$management_card];
        }

        //员工卡登陆
        $employee = Employee::where('card_number',$card_number)->with(['job_type'=>function($q){
            return $q->select('id','job_type','print_num');
        }])->first();
        if(!$employee){
            return ['code'=>5002,'data'=>[],'msg'=>'卡号不存在'];
        }
        $info = User::find($employee->user_id);
        if (!$info) {
            return ['code'=>1021,'data'=>[],'msg'=>'账号异常，请联系管理员'];
        }
        // 使用状态校验
        if ($info->status != 1) {
            return ['code'=>1009,'msg'=>'账户不可用,请联系管理员','data'=>[]];
        }
        $employee->is_admin = 2;
        $arr = (new EmployeeRep())->setEmployeeInfo($employee->user_id);
        $employee->details = $arr;
        return ['code'=>0,'msg'=>'','data'=>$employee];

    }


    /**
     * 获取用户列表
     * @param $params
     */
    public function getUserListRep($params){
        return User::Search($params)
//            ->where(function($q){
//
//                $userIdArr = UserRole::where('role_id','<>',16)->pluck('user_id')->toArray();
//                $q->whereIn('id',$userIdArr);
//            })
            ->select("id",'username','password',"company_name","token",'last_login_time','last_login_ip','expire_time','phone','is_primary')
            ->with(['role'])->orderBy("id","desc")
            ->paginate($params['per_page']??100);

//        return UserRole::Search($params)
//            ->with(['user','role'])
//            ->orderBy('user_id','desc')
//            ->paginate($params['per_page']??100);
    }

    /**
     * 添加子账号
     * @param $params
     */
    public function createUserRep($params){
        DB::beginTransaction();
        try {
            if(isset($params['id']) && !empty($params['id'])){
                //编辑
                $user = User::where('id',$params['id'])->first();
                $user->company_name = $params['company_names'];
                $user->phone = $params['phones'];
                $user->username = $params['usernames'];
                $user->password = $params['passwords']??123456;

            }else{
                $user = User::where('username',$params['usernames'])->first();
                if(!$user){
                    $user = new User();
                }
                $user->username = $params['usernames'];
                $user->password = $params['passwords']??123456;
                $user->phone = $params['phones'];
                $user->company_name = $params['company_names'];
                $user->parent_username = $params['parent_username'];
            }
            $user->is_del = 2;
            $user->save();
            $where = ['user_id'=>$user->id];
            UserRole::updateOrCreate($where,['role_id'=>$params['roles_id']]);
            DB::commit();
            return ['code'=>0,'data'=>$user,'msg'=>''];
        }catch(\Exception $e){
            DB::rollBack();
            return ['code'=>2001,'data'=>[],'msg'=>$e->getMessage()];
        }
    }

    /**
     * 修改用户状态
     * @param $params
     */
    public function setUserStatusRep($params){
        $model = User::where('id',$params['id'])->first();
        $model->status = $params['status'];
        $model->save();
        $saveData = self::getUserKeysValue($model);
        self::resetUserTokenValue($model->token,$saveData);
        return $model;
    }

    /**
     * 获取员工详细信息
     * @param $params
     */
    public function getUserInfoRep($params){
        $role_id = $params['role_id'];
        if($role_id == 16){
            $employee = Employee::where('user_id',$params['user_id'])->with('job_type')->first();
            $params['job_type'] = $employee->job_type->job_type;
        }
        return $params;
    }


    /**
     * 修改密码
     * @param $params
     */
    public function changePasswordRep($params){
        $model = User::where('id',$params['user_id'])->first();
        if($params['old_password'] != $model->password){
            return ['code'=>2001,'data'=>[],'msg'=>'原始密码错误'];
        }
        self::removeToken($model->token);
        $model->password = $params['new_password'];
        $model->token = '';
        //$model->expire_time = '';
        $model->save();
        return ['code'=>0,'data'=>$model,'msg'=>''];
    }

    /**
     * 删除用户
     * @param $params
     */
    public function delUserRep($params){
        $model = User::where('id',$params['users_id'])->first();
        DB::beginTransaction();
        try {
            if($params['users_id'] == 1){
                return ['code'=>2001,'data'=>[],'msg'=>'超级管理员不能删除'];
            }
            UserRole::where('user_id',$params['users_id'])->delete();
            Employee::where('user_id',$params['users_id'])->update(['is_del'=>1]);
            $model->is_del = 1;
            $model->save();
            DB::commit();
            return ['code'=>0,'data'=>[],'msg'=>''];
        }catch(\Exception $e){
            DB::rollBack();
            return ['code'=>2001,'data'=>[],'msg'=>$e->getMessage()];
        }
    }



}
